<template>
  <div class="g-page-container">
    <PageHeader title="拜访事项跟进" />
    <div class="g-content-container">
      <SearchForm
        ref="search-form"
        @search="getList"
        @down-matter-list="downMatterList"
      />
      <ButtonGroup :options="buttons" @click="handleButtonClick" />
      <TableList
        :scroll="{ x: '100%', y: 'calc(100vh - 450px)' }"
        :pagination="paginationMixin"
        :loading="loading"
        :data-source="dataSource"
        :plan-type="planType"
        :row-selection="rowSelectionMixin"
        @change="handleTableChange"
        @number-click="handleNumberClick"
      />
      <component
        :is="currentComponent"
        :is-cancel-visit.sync="isCancelVisit"
        :title-info="titleInfo"
        :visible.sync="visibleDrawer"
        :add-state.sync="addState"
        :detail="detail"
        @fresh="getList(true)"
      />
      <DialogTransferAdminMatter
        :visible.sync="visibleModal"
        :plan-id="planId"
        :selecteds="selectedInfos"
        number="事项编号"
        @fresh="getList(true)"
      />
    </div>
  </div>
</template>

<script>
import SearchForm from './components/SearchForm.vue';
import ButtonGroup from '@/components/button/ButtonGroup.vue';
import TableList from './components/TableList.vue';
import DialogTransferAdminMatter from '@/components/dialog/DialogTransferAdminMatter.vue';
import mixinTable from '@/mixins/mixin-table.js';
import DrawerMatter from './components/DrawerMatter.vue';
import {
  postMatterList,
  postDownMatterlist,
  getMatterInfo,
} from '@/api/mattre.js';
import { downloadFile } from '@/utils/index.js';

export default {
  components: {
    SearchForm,
    ButtonGroup,
    TableList,
    DrawerMatter,
    DialogTransferAdminMatter,
  },
  mixins: [mixinTable],
  data() {
    return {
      visibleDrawer: false,
      currentComponent: 'DrawerMatter',
      columnKey: '',
      loading: false,
      detail: {},
      addState: false,
      titleInfo: {},
      isCancelVisit: false,
      visibleModal: false,
      selectedInfos: [],
    };
  },
  computed: {
    buttons() {
      const disabled = !this.rowSelectionMixin.selectedRowKeys.length;
      return [
        {
          key: 'retweet',
          label: '转他人处理',
          icon: 'retweet',
          authKey: 'matter-button-transfer',
          disabled,
        },
      ];
    },
  },
  created() {
    this.getList(true);
  },
  methods: {
    async retweetCallback() {
      const selectedInfos = this.rowSelectionMixin.selectedRows
        .filter((item) => item.nodeCode === '1')
        .map((item, i) => {
          return {
            serialNumber: item.matterNo,
            currentUserId: item.currentUserId,
            planId: item.id,
          };
        });
      console.log(this.rowSelectionMixin.selectedRows);
      if (!selectedInfos.length) {
        this.$message.info(
          `仅可转待处理的数据，现有 ${selectedInfos.length} 条！`
        );
        return;
      }
      try {
        await this.$confirm(
          `仅可转审批中的数据，共 ${selectedInfos.length} 条，是否确认？`
        );

        this.visibleModal = true;
        this.selectedInfos = selectedInfos;
        console.log('selectedInfos: ', selectedInfos);
      } catch (error) {
        // console.log('error: ', error);
      }
    },
    getSearchForm() {
      const form = this.$refs['search-form']?.form || {};
      const page = {
        current: this.paginationMixin.current,
        pageSize: this.paginationMixin.pageSize,
        asc: this.asc,
        column: this.columnKey,
      };
      return { ...form, ...page };
    },
    async getList(val) {
      this.loading = true;
      this.rowSelectionMixin.selectedRowKeys = [];
      if (val) {
        let form = this.$refs['search-form']?.form || {};
        this.paginationMixin = {
          pageSizeOptions: ['10', '20', '50', '100'],
          showSizeChanger: true,
          // showQuickJumper: true,
          current: 1,
          pageSize: 10,
          total: 0,
        };
        const page = {
          current: this.paginationMixin.current,
          pageSize: this.paginationMixin.pageSize,
        };
        form = { ...form, ...page };
        const result = await postMatterList(form).finally(
          () => (this.loading = false)
        );
        this.paginationMixin.total = result.data.data?.total;
        this.dataSource = result?.data?.data?.records || [];
      } else {
        const form = this.getSearchForm();
        const result = await postMatterList(form).finally(
          () => (this.loading = false)
        );

        this.paginationMixin.total = result.data.data?.total;
        this.dataSource = result?.data?.data?.records || [];
      }
    },
    handleButtonClick(key) {
      console.log(key);
      const fn = `${key}Callback`;
      this[fn] && this[fn]();
    },

    async downMatterList() {
      const form = this.getSearchForm();
      const res = await postDownMatterlist(form);
      await downloadFile(res.data, res.filename || '跟进事项信息列表.xlxs');
    },

    handleTableChange(page, filters, sorter, { currentDataSource }) {
      this.asc = sorter.order === 'ascend' ? true : false;
      this.columnKey = sorter.columnKey;
      this.paginationMixin = page;
      this.getList(false);
    },

    async handleNumberClick(record) {
      const result = await getMatterInfo(record.id);
      console.log('result: ', result);
      this.detail = result?.data.data;
      this.currentComponent = 'DrawerMatter';
      this.addState = false;
      this.visibleDrawer = true;
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      if (to.query?.id) {
        vm.handleNumberClick(to.query);
      }
    });
  },
};
</script>
